package io.mvvm.security.handler;

import com.alibaba.fastjson.JSON;
import io.mvvm.common.constant.SystemConstants;
import io.mvvm.common.enumerate.ResponseEnum;
import io.mvvm.common.entity.AjaxResponse;
import io.mvvm.utils.RedisUtil;
import io.mvvm.ws.WebSocketChannelHolder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: seize-login
 * @description: 登出成功
 * @author: 潘
 * @create: 2021-05-14 22:40
 **/
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        String key = SystemConstants.append(SystemConstants.LOGIN_STATUS, userDetails.getUsername());
        redisUtil.del(key);
        WebSocketChannelHolder.removeChannel(userDetails.getUsername());

        AjaxResponse response = AjaxResponse.success(ResponseEnum.LOGOUT_SUCCESS, null, null);

        httpServletResponse.setContentType("application/json; charset=utf-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(response));
    }
}
